package com.example.jdbc.login;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;

/**
 * 模拟用户登录
 * 使用 Statement SQL 拼接时存在SQL注入风险，例如 密码输入为：****' or '1'='1，在不正确的情况下也可返回数据
 * SQL注入的根本是什么？
 *  用户输入的信息中含有SQL语句的关键字，并且这些关键字参与SQL语句的编译过程，
 *  导致SQL语句的原意被扭曲，进而达到SQL注入。
 *  可以使用 PreparedStatement 放置SQL注入
 */
public class LoginDemo {
    public static void main(String[] args) {
        Map<String, String> userInfo = initUI();
        boolean loginSuccess = login(userInfo);
    }

    private static boolean login(Map<String, String> userInfo) {
        boolean loginSuccess = false;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://192.168.31.92:3306/muser", "root", "123456");
            stmt = conn.createStatement();
            String sql = " select * from muser where username = '"+ userInfo.get("username")+"' and password = '"+userInfo.get("password")+"' ";
            ResultSet resultSet = stmt.executeQuery(sql);
            if (resultSet.next()) {
                loginSuccess = true;
                System.out.println("login successfully");
                return loginSuccess;
            } else {
                System.out.println("login failed");
                return loginSuccess;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(rs)) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (Objects.nonNull(stmt)) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (Objects.nonNull(conn)) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return loginSuccess;
    }

    private static Map<String, String> initUI() {
        Scanner s = new Scanner(System.in);
        System.out.print("用户名： ");
        String username = s.nextLine();
        System.out.print("密码：");
        String password = s.nextLine();
        Map<String,String> userInfo = new HashMap<>();
        userInfo.put("username", username);
        userInfo.put("password", password);
        return userInfo;
    }


}
